package org.maurange.formation.licpro;

import java.util.ArrayList;
import java.util.List;

import org.maurange.formation.licpro.rest.Arret;
import org.maurange.formation.licpro.rest.ArretRestMethod;
import org.maurange.formation.licpro.rest.ListArret;

import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.NetworkInfo.DetailedState;
import android.os.AsyncTask;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;



public class ListArretsActivity extends ListActivity implements LocationListener{
	
	private static String LOG_TAG="ListArretsActivity";
	private CallWebServiceAsyncTask task;
	private LocationManager lm;
	
	private ArretAdapter arretAdapter;
	
	//geoloc
	private double latitude;
	private double longitude;
	private double altitude;
	private float accuracy;
	
    @Override
    protected void onCreate(Bundle savedInstanceState)  {
        super.onCreate(savedInstanceState);
        task = (CallWebServiceAsyncTask) getLastNonConfigurationInstance();
        
        arretAdapter = new ArretAdapter(this, new ArrayList<Arret>());
        setListAdapter(arretAdapter);
        
        getListView().setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				launchTempsAttenteActivity(arretAdapter.getListArret().get(position));
			}
		});
    }
    
    public void launchTempsAttenteActivity(Arret a){
    	Intent myIntent = new Intent(this, TempsAttenteActivity.class);
		myIntent.putExtra("code_lieu", a.getCodeLieu());
		myIntent.putExtra("name_arret", a.getLibelle());
        startActivity(myIntent);
    }

    public Object onRetainNonConfigurationInstance(){
    	task.detach();
    	return task;
    }
    

	protected void onResume() {
		super.onResume();
		Log.d(LOG_TAG, "enregistrement des listeners");
		
		lm = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
		if (lm.isProviderEnabled(LocationManager.GPS_PROVIDER)){
			Log.d(LOG_TAG, "calling : getLastKnownLocation");
			lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
			Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
			
			if (task != null){
	        	relaunchTask(location);
	        }
	        else{
		        //appel de l'asynctask
		        ListArretsActivity.this.task = new CallWebServiceAsyncTask(this, arretAdapter);
		        Log.d(LOG_TAG, "LOCATION : long = " +  location.getLatitude() +" lat = "+ location.getLongitude());
		        task.execute(location.getLatitude(), location.getLongitude());
	        }
		}
	}
	
	private void relaunchTask(Location location) {
		task.detach();
		task.cancel(true);
    	task = new CallWebServiceAsyncTask(this, arretAdapter); 
    	task.execute(location.getLatitude(), location.getLongitude());
	}

	@Override
	public void onLocationChanged(Location location) {
		latitude = location.getLatitude();
		longitude = location.getLongitude();
		altitude = location.getAltitude();
		accuracy = location.getAccuracy();
		if ((task.getStatus().equals(AsyncTask.Status.RUNNING)) || (task.getStatus().equals(AsyncTask.Status.PENDING))) {
			task.cancel(true);
		}
		ListArretsActivity.this.task = new CallWebServiceAsyncTask(this, arretAdapter);
		try{
			task.execute(latitude, longitude);
		}catch (Exception e) {}
		
	}

	//location
	@Override
	public void onProviderDisabled(String arg0) {
		Log.d(LOG_TAG, "provider disabled");
	}

	@Override
	public void onProviderEnabled(String arg0) {
		Log.d(LOG_TAG, "provider enablezd");
	}

	@Override
	public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
		Log.d(LOG_TAG, "changed");
	}
	
	//arret des updates
	@Override
	protected void onPause() {
		super.onPause();
		Log.d(LOG_TAG, "desenregistrement des listeners");
		lm.removeUpdates(this);
	}

	static private class CallWebServiceAsyncTask extends AsyncTask<Double, Void, ListArret>{
		private ArretRestMethod rest;
		private Activity activity;
		private  ArretAdapter adapter;
		
		public CallWebServiceAsyncTask(Activity activity, ArretAdapter arretAdapter){
			this.activity = activity;
			rest = new ArretRestMethod(activity);
			this.adapter = arretAdapter;
		}
		
		protected ListArret doInBackground(Double... params) {
			return rest.getArretsRest(params[0], params[1]);
		}
		
		protected void onPostExecute(ListArret arrets){
			try{
				adapter.getListArret().clear();
			}catch (Exception e) {}
			adapter.getListArret().addAll(arrets);
			adapter.notifyDataSetChanged();
		}
		
		public void detach(){
			this.activity = null;
		}
		
		public void attach(Activity a){
			this.activity = a;
		}

	}

}
